import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElIcon,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElMessage,
  ElSpace,
  ElLink,
  ElPagination,
  ElTable,
  ElTableColumn
} from 'element-plus'
import {
  EditPen
  // MapLocation
} from '@element-plus/icons-vue'
import type { CourtsType, mapMarderViewPropsType } from './typings'

import type { isPlanEnum } from '~/store/oam/tour/typings'

import useVuexGetters from '~/hooks/useVuexGetters'
import MapInfoView from './mapInfoView'
import SearchForm from '~/components/ProForm/SearchForm'

export default defineComponent({
  props: ['visible', 'moduleId', 'list'],
  emits: ['cancel', 'confirm'],
  setup(props, { emit }) {
    const store = useStore()
    const multipleTableRef = ref<InstanceType<typeof ElTable>>()
    const formValues = reactive<CourtsType>({})
    const tourState = useVuexGetters('tour', ['isPlanOpt'])
    const mapstate = reactive<mapMarderViewPropsType>({
      id: 'mapView',
      visible: false,
      markers: []
    })
    const paginationState = reactive({
      current: 1,
      size: 10,
      moduleId: ''
    })
    const ids = reactive({
      value: [] as any[]
    })
    let total = 0
    const listData = ref([])
    // const columns: TableColumnProps<CourtsType>[] = [
    //   {
    //     label: '台区名称',
    //     prop: 'assetName',
    //     showOverflowTooltip: true,
    //     minWidth: 160
    //   },
    //   {
    //     label: '所属工区',
    //     prop: 'workAreaName',
    //     minWidth: 160
    //   },
    //   {
    //     label: '台区地址',
    //     prop: 'address',
    //     showOverflowTooltip: true,
    //     minWidth: 200
    //   },
    //   {
    //     label: '是否加入巡视计划',
    //     prop: 'isPlan',
    //     minWidth: 160,
    //     render: (_, value) => {
    //       return <>{value === 1 ? '是' : '否'}</>
    //     }
    //   },
    //   {
    //     label: '所属巡视分组',
    //     prop: 'groupName',
    //     minWidth: 120
    //   },
    //   {
    //     label: '操作',
    //     prop: 'options',
    //     minWidth: 120,
    //     unFixed: true,
    //     fixed: 'right',
    //     render: ({ row }) => (
    //       <ElSpace>
    //         <ElLink icon={MapLocation} type="primary" onClick={() => mapInfo(row)}>
    //           &nbsp;地图
    //         </ElLink>
    //       </ElSpace>
    //     )
    //   }
    // ]

    //  显示地图
    const mapInfo = (row: any) => {
      if (!row.phase) {
        ElMessage({ type: 'warning', message: '当前台区未上传定位信息' })
        return
      }
      const array: { id: any; latitude: any; longitude: any }[] = []
      const phase = JSON.parse(row.phase)
      array.push({
        id: row.assetId,
        longitude: Number(phase.coordinates[0]),
        latitude: Number(phase.coordinates[1])
      })
      mapstate.markers = array
      mapstate.visible = !mapstate.visible
    }
    //  关闭地图
    const mapMarkerCancel = () => {
      mapstate.visible = !mapstate.visible
    }
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }
    //  列表数据
    const init = async () => {
      const { list, moduleId } = props
      ids.value = list
      paginationState.moduleId = moduleId
      Object.assign(paginationState, formValues)
      const { code, data } = await store.dispatch('tour/GetSllAssetPage', paginationState)
      if (code === 200) {
        if (data.records.length > 0) {
          listData.value = data.records
          total = data.total
          data.records.forEach((item: any) => {
            list.forEach((row: any) => {
              if (item.assetId === row.assetId) {
                nextTick(() => {
                  multipleTableRef.value!.toggleRowSelection(item, true)
                })
              }
            })
          })
        }
      }
    }
    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      paginationState.current = 1
      if ((evt as KeyboardEvent).key === 'Enter') init()
    }
    // 清空搜索
    const clearSearchTable = async () => {
      paginationState.current = 1
      setTimeout(() => {
        init()
      }, 100)
    }
    //  搜索
    const handleSearchList = () => {
      paginationState.current = 1
      init()
    }
    //  每页数量
    const onSizeChange = (value: any) => {
      paginationState.size = value
      init()
    }
    //  分页
    const onCurrentChange = (value: any) => {
      paginationState.current = value
      init()
    }
    //  列表勾选
    const onSelect = (selection: any) => {
      ids.value = selection
    }
    //  全选
    const onSelectAll = (selection: any) => {
      ids.value = selection
    }
    //  确定
    const confirm = () => {
      // const array = proSaasTableRef.value!.selecteds
      if (ids.value.length === 0) {
        ElMessage({ type: 'warning', message: '请勾选数据' })
        return
      }
      emit('confirm', ids.value)
      handleCloseModal()
    }
    onMounted(() => {
      const { moduleId } = props
      formValues.moduleId = moduleId
      init()
    })

    return () => {
      const { visible } = props
      return (
        <ElDialog
          width="75%"
          title={'选择台区'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={{
            footer: () => (
              <>
                <ElButton type="primary" onClick={confirm}>
                  <ElIcon>
                    <EditPen />
                  </ElIcon>
                  &nbsp; 确定
                </ElButton>
                <ElButton onClick={handleCloseModal}>取消</ElButton>
              </>
            )
          }}
        >
          <SearchForm
            searchFormProps={{
              model: formValues
            }}
            handleSearchList={handleSearchList}
            searchformResponsiveCol={[
              <ElFormItem key="assetName" prop="assetName" label="">
                <ElInput
                  v-model={formValues.assetName}
                  placeholder="请输入台区搜索"
                  clearable
                  onKeydown={handleKeyDownEnterSubmitForm}
                  onClear={clearSearchTable}
                />
              </ElFormItem>,
              <ElFormItem key="isPlan" prop="isPlan" label="">
                <ElSelect
                  v-model={formValues.isPlan}
                  clearable
                  onChange={clearSearchTable}
                  placeholder="是否加入巡视计划"
                >
                  {tourState.isPlanOpt?.value?.map((item: isPlanEnum) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id} />
                  ))}
                </ElSelect>
              </ElFormItem>
            ]}
          />
          <ElTable
            data={listData.value}
            ref={multipleTableRef}
            row-key="assetId"
            border
            onSelect={onSelect}
            onSelect-all={onSelectAll}
          >
            <ElTableColumn type="selection" reserve-selection />
            <ElTableColumn prop="assetName" label="台区名称" />
            <ElTableColumn prop="workAreaName" label="所属工区" />
            <ElTableColumn prop="assetAddress" show-overflow-tooltip label="台区地址" />
            <ElTableColumn
              prop="isPlan"
              align="center"
              label="是否加入巡视计划"
              v-slots={{ default: ({ row }: any) => <>{row.isPlan === 1 ? '是' : '否'}</> }}
            />
            <ElTableColumn prop="groupName" label="所属巡视分组"></ElTableColumn>
            <ElTableColumn
              label="操作"
              v-slots={{
                default: ({ row }: any) => (
                  <>
                    <ElSpace>
                      <ElLink type="primary" onClick={() => mapInfo(row)}>
                        &nbsp;地图
                      </ElLink>
                    </ElSpace>
                  </>
                )
              }}
            />
          </ElTable>

          <div style="height: 10px;"></div>
          <ElPagination
            v-model:currentPage={paginationState.current}
            v-model:pageSize={paginationState.size}
            layout="total, sizes, prev, pager, next, jumper"
            background={true}
            small={true}
            total={total}
            onSize-change={onSizeChange}
            onCurrent-change={onCurrentChange}
          />
          {/* 查看地图 */}
          {mapstate.visible && (
            <MapInfoView
              id={mapstate.id}
              visible={mapstate.visible}
              onCancel={mapMarkerCancel}
              markers={mapstate.markers}
            />
          )}
        </ElDialog>
      )
    }
  }
})
